<template>
    <div class="form-container">
        <div class="form-item">
            <label for="type">类型：</label>
            <el-select v-model="typeValue" placeholder="选择题目类型" clearable>
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
        </div>
        <div class="form-item">
            <label for="section">章节：</label>
            <el-select v-model="sectionValue" placeholder="选择章节" clearable>
                <el-option v-for="item in sectionData" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
        </div>
        <div class="form-item">
            <label for="content">题目：</label>
            <el-input v-model="content" type="textarea" placeholder="输入题目" />
        </div>
        <div v-if="typeValue=='1' || typeValue=='2'">
            <!-- 数字选择框 -->
             <label for="count">选项个数:</label>
             <br>
            <el-input-number v-model="optionCount" @change="generateOptions" :min="1" :max="26" label="选项数量"
                placeholder="输入选项数量" style="margin-bottom: 20px; width: 200px" />

            <!-- 动态生成选项 -->
            <div v-for="(item, index) in inputs" :key="index" class="input-row">
                <!-- 单选框 -->
                <el-radio v-if="typeValue == '1'" v-model="selectedOption" :label="item.label"
                    style="margin-right: 10px">
                    {{ item.label }}
                </el-radio>

                <!-- 多选框 -->
                <el-checkbox v-if="typeValue == '2'" v-model="item.selected" @change="updateSelectedOptions"
                    style="margin-right: 10px">
                    {{ item.label }}
                </el-checkbox>

                <!-- 左边默认值输入框 -->
                <el-input v-model="item.label" style="width: 50px; margin-right: 10px" />

                <!-- 右边内容输入框 -->
                <el-input v-model="item.value" :placeholder="'请输入选项内容 ' + (index + 1)" style="width: 300px" />
            </div>

            <!-- 显示选中的选项 -->
            <div class="selected-options" v-show="false">
                <h3>已选中的选项:</h3>
                <p v-if="typeValue == '1' && !selectedOption">暂无选中选项</p>
                <p v-else-if="typeValue === '1'">单选: {{ selectedOption }}</p>

                <p v-if="typeValue === '2' && selectedOptions.length === 0">暂无选中选项</p>
                <ul v-else-if="typeValue === '2'">
                    <li v-for="(option, index) in selectedOptions" :key="index">
                        {{ option.label }}: {{ option.value }}
                    </li>
                </ul>
            </div>
        </div>
        
        <el-radio-group v-if="typeValue == 3" v-model="radioValue">
            <label for="answer">答案：</label>
            <el-radio value="T" size="large">√</el-radio>
            <el-radio value="F" size="large">×</el-radio>
        </el-radio-group>
        <div class="form-item" v-if="typeValue == 4 || typeValue == 5">
            <label for="answer">答案：</label>
            <el-input v-model="answer" placeholder="输入答案" />
        </div>
        <div class="form-item">
            <label for="analysis">解析：</label>
            <el-input v-model="analysis" type="textarea" placeholder="输入解析" />
        </div>
        
        <div class="form-item">
            <label>图片上传：</label>
            <el-upload class="upload-demo" :file-list="fileList" :on-change="handleFileChange" :auto-upload="false"
                list-type="picture">
                <el-button type="primary">选择图片</el-button>
                <template #tip>
                    <div class="el-upload__tip">
                        请上传 jpg/png 格式的文件，大小不超过 500kb
                    </div>
                </template>
            </el-upload>
        </div>
        <div class="form-submit">
            <el-button type="success" @click="submitForm">提交</el-button>
        </div>
    </div>
</template>

<script setup lang="js">
import { onMounted, ref } from 'vue';
import request from '@/util/request';

const radioValue = ref('');
const typeValue = ref('1');
const sectionValue = ref('');
const content = ref('');
const answer = ref('');
const sectionData = ref([]);
const fileList = ref([]);
const optionCount = ref(4); // 默认选项数量
const inputs = ref([]); // 存储选项数据
const selectedOption = ref(null); // 单选框的选中值
const selectedOptions = ref([]); // 多选框的选中数组
const analysis = ref('');
// 初始化选项
const generateOptions = () => {
    inputs.value = Array.from({ length: optionCount.value }, (_, index) => ({
        label: String.fromCharCode(65 + index), // 默认 A, B, C...
        value: "", // 用户输入内容
        selected: false, // 多选框是否选中
    }));
};

// 更新选中选项
const updateSelectedOptions = () => {
    selectedOptions.value = inputs.value.filter((item) => item.selected);
};

// 初始化时生成默认选项
generateOptions();

onMounted(async () => {
    const res = await request.post('/section/list/', { subject_id: 2 });
    // console.log(res.data.data.knowledge_points);
    const res2= await request.post('/section/list/', { subject_id: 3 });
    let array=[]
    let sectionArray= res.data.data.knowledge_points;
    let sectionArray2= res2.data.data.knowledge_points;
    for (let i = 0; i < sectionArray2.length; i++) {
        let name= sectionArray2[i].name;
        for (let j = 0; j < sectionArray2[i].sections.length; j++) {
            sectionArray2[i].sections[j].name=name+"/"+sectionArray2[i].sections[j].name
            array.push(sectionArray2[i].sections[j])
        }
    }
    for (let i = 0; i < sectionArray.length; i++) {
        let name= sectionArray[i].name;
        for (let j = 0; j < sectionArray[i].sections.length; j++) {
            sectionArray[i].sections[j].name=name+"/"+sectionArray[i].sections[j].name
            array.push(sectionArray[i].sections[j])
        }
    }
    
    sectionData.value = array || [];
});

const options = [
    { label: '单选题', value: '1' },
    { label: '多选题', value: '2' },
    { label: '判断题', value: '3' },
    { label: '填空题', value: '4' },
    { label: '解答题', value: '5' },
];

const handleFileChange = (file) => {
    if (file.raw) fileList.value = [file.raw];
};

const submitForm = async () => {
    const formData = new FormData();
    formData.append('type', typeValue.value);
    formData.append('section_id', sectionValue.value);
    formData.append('images', fileList.value[0]);
    formData.append('analysis', analysis.value);
    // 选项
    const uploadOptions = inputs.value.map((item) => ({
        key: item.label,
        value: item.value,
    }))
    if (typeValue.value == '1' || typeValue.value == '2') {
        formData.append('content', JSON.stringify({ stem: content.value, options: uploadOptions }));
    }
    if (typeValue.value == '1') {
        let arr = []
        arr.push(selectedOption.value)
        formData.append('answer',  JSON.stringify(arr));
    }
    if (typeValue.value == '2') {
        
        // 提取 label 和 value
        const result = selectedOptions.value.map(option => ({
            label: option.label,
            value: option.value,
        }));
        let arr2=[]
        result.forEach((item) => {
            arr2.push(item.label)
            console.log("Selected Option:", item);
        })
        formData.append('answer', JSON.stringify(arr2));
    }
    if(typeValue.value == '3'){
        let arr3=[]
        arr3.push(radioValue.value);
        formData.append('answer', JSON.stringify(arr3));
        formData.append('content', JSON.stringify({ stem: content.value,options:[
            {
                key: 'T',
                value: '正确'
            },
            {
                key: 'F',
                value: '错误'
            }
        ] }));
    }
    if(typeValue.value == '4'||typeValue.value == '5'){
        formData.append('content', JSON.stringify({ stem: content.value }));
        formData.append('answer', answer.value);
    }
    for (const [key, value] of formData.entries()) {
        console.log(`${key}: ${value}`);
    }
    try {
        const res = await request.post('/admin/question/upload/', formData);
        console.log('上传成功', res.data);
    } catch (err) {
        console.error('上传失败', err);
    }
};

</script>

<style scoped lang="less">
.form-container {
    max-width: 600px;
    margin: 20px auto;
    padding: 20px;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-item {
    margin-bottom: 20px;
}

label {
    display: inline-block;
    margin-bottom: 8px;
    font-size: 14px;
    font-weight: 500;
}

.el-input,
.el-select {
    width: 100%;
}

.el-upload {
    display: block;
}

.form-submit {
    text-align: center;
}
</style>